package org.csu.small.handler;

import org.csu.small.common.UniformResponse;
import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice(basePackages = "org.csu.small.controller")
public class RestExceptionHandler {

    //运行时异常
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public UniformResponse<String> runtimeExceptionHandler(RuntimeException runtimeException) {

        return UniformResponse.createForErrorMessage("RuntimeException");
    }

    //参数类型不匹配
    //getPropertyName()获取数据类型不匹配参数名称
    //getRequiredType()实际要求客户端传递的数据类型
    @ExceptionHandler(TypeMismatchException.class)
    @ResponseBody
    public UniformResponse<String> requestTypeMismatch(TypeMismatchException ex){
        ex.printStackTrace();
        return UniformResponse.createForErrorMessage("参数类型不匹配,参数" + ex.getPropertyName() + "类型应该为" + ex.getRequiredType());
    }

    //参数类型不匹配
    //getPropertyName()获取数据类型不匹配参数名称
    //getRequiredType()实际要求客户端传递的数据类型
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public UniformResponse<String> requestObTypeMismatch(BindException ex){
        ex.printStackTrace();
        return UniformResponse.createForErrorMessage("参数类型不匹配");
    }
    //缺少参数异常
//getParameterName() 缺少的参数名称
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public UniformResponse<String> requestMissingServletRequest(MissingServletRequestParameterException ex){
        ex.printStackTrace();
        return UniformResponse.createForErrorMessage("缺少必要参数,参数名称为" + ex.getParameterName());
    }
}
